<?php
namespace app\admin\model;

use think\Config;
use think\Db;
use think\Model;
use think\Session;

class AdvertyModel extends Model
{
	/**
	*	获取商品信息
	*/
	public function getGoods()
	{
		$where = [];
		$where['g_status'] = 2;
		$where['g_type'] = 2;
		$res = Db::table('sz_goods')->where($where)->select();
		return $res;
	}

	/**
	*	广告列表
	*/
	public function getFlash($data)
	{
		$where = [];

		/* 商品名称 */
		$gid = empty($data['gid']) ? '' : $data['gid'];
		$gid = trim($gid);
		if(!empty($gid)){
			$where['a.gid'] = $gid;
		}

		/* 状态 */
		$status = empty($data['status']) ? '' : $data['status'];
		$status = trim($status);
		if(!empty($status)){
			$where['a.status'] = $status;
		}

		$join = [

			['sz_goods g','a.gid=g.id','left']
		];

		$result = Db::table('sz_advertising')->alias('a')
				->join($join)
				->field('a.*,g.g_name')
				->where($where)
				->order('a.id ASC')
				->paginate(20,false,['query' => request()->param()]);

		return $result;
	}

	/**
	*	添加广告
	*/
	public function addFlash($data)
	{

	   	// 将添加时间转为时间戳
	    $data['addtime']    = empty( $data['addtime']) ? 0 : strtotime($data['addtime']);

	    $res = Db::table('sz_advertising')->insert($data);

	    if($res){
	    	return true;
	    }else{
	    	return false;
	    }
	}

	/**
	*	获取一个广告
	*/
	public function getOne($id)
	{
		if($id){
			$res = Db::table('sz_advertising')->where('id',$id)->find();
			return $res;
		}
	}

	/**
	*	修改一个广告
	*/
	public function editFlash($id,$data)
	{
		// 将添加时间转为时间戳
	    $data['addtime'] = empty( $data['addtime']) ? 0 : strtotime($data['addtime']);

	    $res = Db::table('sz_advertising')->where('id',$id)->update($data);

	    if($res){
	    	return true;
	    }else{
	    	return false;
	    }
	}

	/**
	*	删除广告
	*/
	public function deleteFlash($id)
	{
		$res = Db::table('sz_advertising')->where('id',$id)->find();
		if($res['status']==2){
			return 2;
		}else{
			Db::table('sz_advertising')->where('id',$id)->delete();
			return 1;
		}
	}

	/**
	*	批量上架
	*/
	public function racking($data)
	{
		$aryid = rtrim($data['id'],','); // 去掉最右边的逗号
		$aryid = explode(",",$aryid);

		// 更新内容
		$map['status'] = 2;		
		$map['addtime'] = strtotime(date('Y-m-d H:i',time()));
 		foreach ($aryid as $key => $val) {
			$res = Db::table('sz_advertising')->where('id='.$val)->update($map);		
		}
		if($res){
			return true;
		}else{
			return false;
		}
	}

	/**
	*	批量下架
	*/
	public function rack($data)
	{
		$aryid = rtrim($data['id'],','); // 去掉最右边的逗号
		$aryid = explode(",",$aryid);

		// 更新内容
		$map['status'] = 3;
		$map['addtime'] = strtotime(date('Y-m-d H:i',time()));

		foreach ($aryid as $key => $val) {
			$res = Db::table('sz_advertising')->where('id='.$val)->update($map);		
		}
		if($res){
			return true;
		}else{
			return false;
		}
	}
}